package com.teamview.view;

import java.util.Scanner;

/**
 * @author Lenl
 * @create 2021-06-01 21:33
 * @Description 用来方便实现键盘访问
 *
 *
 */
public class TSUtility {
    private static Scanner scanner=new Scanner(System.in);

    /**
     * @Description 读取键盘。1-4字符合法
     * @return 用户返回的字符
     */
    public static char readMenuSelection(){
        char c;
        for (;;){
            String str=readKeyBoard(1,false);
            c=str.charAt(0);
            if(c!='1'&&c!='2'&&c!='3'&&c!='4'){
                System.out.print("选择错误，请重新输入：");
            }else break;
       }
        return c;
    }

    /**
     * 提示并等待，到用户按回车键后返回
     */
    public static void readReturn(){
        System.out.print("按回车键继续...");
        readKeyBoard(100,true);
    }

    /**
     * 从键盘读取长度不超过2的整数
     * @return 长度不超过2的整数
     */
    public static int readInt(){
        int n;
        for (;;){
            String str=readKeyBoard(2,false);
            try {
                n=Integer.parseInt(str);
                break;
            }catch (NumberFormatException e){
                System.out.print("数字输入错误，请重新输入：");
            }
        }
        return n;
    }

    public static char readConfirmSelection(){
        char c;
        for (;;){
            String str=readKeyBoard(1,false).toUpperCase();
            c=str.charAt(0);
            if(c=='Y'||c=='N'){
                break;
            }else{
                System.out.print("选择错误，请重新输入：");
            }
        }
        return  c;
    }

    public static String readKeyBoard(int limit,boolean blankReturn){
        String line="";

        while(scanner.hasNextLine()){
            line=scanner.nextLine();
            if(line.length()==0){
                if(blankReturn) return line;
                else continue;
            }
            if(line.length()<1||line.length()>limit){
                System.out.print("输入长度(不大于"+limit+")错误，请重新输入：");
                continue;
            }
            break;
        }
        return line;
    }
}
